package com.panshi.config;

import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class AdminConfigShiro {

    // ShiroFilterFactoryBean    过滤对象
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("getDefaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        // 设置 安全管理器
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);

        // 添加shiro 的内置过滤器
        /**
         * anon  无需认证 可以访问
         * authc  必须认证才能访问
         * user  必须拥有 记住我 功能才能访问
         * perms  拥有对某个资源的权限才能访问
         * role  拥有某个角色权限才能访问
         */

        Map<String, String> filterMap = new LinkedHashMap<>();
        // 权限  , 没有授权会跳到未授权页面
//        filterMap.put("/user/add","perms[user:add]");
//        filterMap.put("/user/update","perms[user:update]");
        // 拦截
        filterMap.put("/user/*","authc");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);
        // 设置登录的请求
        shiroFilterFactoryBean.setLoginUrl("/toLogin");

        //设置未授权页面
        shiroFilterFactoryBean.setUnauthorizedUrl("/noauth");
        return shiroFilterFactoryBean;
    }

    // DefaultWebSecurityManager  安全对象
    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("adminLoginRealm") AdminLoginRealm myRealm){
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        // 关联 myRealm
        defaultWebSecurityManager.setRealm(myRealm);
        return defaultWebSecurityManager;
    }
    // 创建 realm  对象 ， 自定义
    @Bean
    public AdminLoginRealm adminLoginRealm(){
        return new AdminLoginRealm();
    }

}
